def majority_element(nums):
    """
    查找出现次数超过一半的元素：摩尔投票法，时间复杂度O(n)
    nums：目标数组
    """
    candidate = None
    count = 0
    for num in nums:
        if count == 0:
            candidate = num
        count += (1 if num == candidate else -1)
    return candidate

# 测试
nums = [3, 2, 3]
print(majority_element(nums))  # 输出：3
nums = [2, 2, 1, 1, 1, 2, 2]
print(majority_element(nums))  # 输出：2